import React, {Component} from 'react';

/**
 * setState use
 */
class SetState extends Component {

    state = {count: 0}

    objAdd = () => {
        // 对象式的setState
        //1. get old value
        const {count} = this.state
        // 2. set new value
        this.setState({count: count + 1})
        // 回调（它在状态更新完毕、render调用后才被调用）
        this.setState({count: count + 1}, () => {
            console.log(this.state.count);
        })
    }

    functionAdd = () => {
        // 函数式的setState
        this.setState((state, props) => {
            return {count: state.count + 2}
        });

        // 简化写法
        //this.setState( state => ({count: state.count + 2}))
    }

    render() {
        return (
            <div>
                <h1> get sum : {this.state.count}</h1>
                <button onClick={this.objAdd}> clickAddOne</button>
                <button onClick={this.functionAdd}> clickAddTwo</button>
            </div>
        );
    }
}

export default SetState;